"""
工具7：数据库查询工具
功能：通用数据库查询
"""
import json
import logging
from langchain.tools import BaseTool

logger = logging.getLogger(__name__)


class DatabaseQueryTool(BaseTool):
    """数据库查询工具"""
    
    name: str = "database_query_tool"
    description: str = """
        通用数据库查询工具（只读）。
        
        输入参数（JSON字符串）：
        {
            "table": "candidate",  // 表名
            "filters": {"city": "杭州"},
            "limit": 10
        }
        """
    
    def _run(self, table: str, filters: str = "{}", limit: int = 10) -> str:
        try:
            # 简化实现：仅支持部分表
            if table == "company":
                from user.models import Company
                query = Company.objects.all()
            elif table == "city":
                from user.models import City
                query = City.objects.all()
            else:
                return json.dumps({
                    "success": False,
                    "error": f"不支持的表: {table}"
                }, ensure_ascii=False)
            
            results = list(query[:limit].values())
            
            return json.dumps({
                "success": True,
                "data": results,
                "message": f"查询到{len(results)}条记录"
            }, ensure_ascii=False)
            
        except Exception as e:
            logger.error(f"数据库查询失败: {str(e)}")
            return json.dumps({
                "success": False,
                "error": str(e)
            }, ensure_ascii=False)
    
    async def _arun(self, *args, **kwargs):
        raise NotImplementedError()


